define(['css!./star-score', 'tpl!./star-score', 'underscore', 'jquery', '../base'], function(css, starTpl, _, $, Base) {
  var ID = 0;
  var clsPrefix = 'star-score-';
  var toNumber = function(v){
    var newV = parseInt(v);
    return (newV === newV) ? newV: 0;
  };

  var emptyStar = '&#xe601;';
  var fillStar = '&#xe600;';

  return Base.extend({
    initializer: function() {
      var self = this;

      self.id  = ID++;
      self.cls = clsPrefix + self.id

      self._render();
      if (self.get('editable')) {
        self._bind();
      }
    },
    _render: function() {
      var self = this;
      var data = {
        width    : self.get('width'),
        height   : self.get('height'),
        interval : self.get('interval'),
        star     : self.get('star'),
        unit     : self.get('unit'),
        cls      : clsPrefix + self.id,
        editable : self.cls
      };
      self.get('el').append(starTpl(data));
    },
    _bind: function() {
      var self = this;
      var stars = $('.'+self.cls+' .star');

      stars.on('click tap', function(){
        var _this = $(this);
        var star = _this.index() + 1;
        self.set('star', star);
      });

      stars.on('mouseover', function(){
        var _this = $(this);
        var star = _this.index() + 1;
        for(var i = 0; i < 5; ++i){
          if(i < star){
            stars.eq(i).html(fillStar);
          }else{
            stars.eq(i).html(emptyStar);
          }
        }
      });

      self.get('el').on('mouseleave', function(){
        self.set('star', self.get('star'));
      });

      self.on('afterChange:star', function(e){
        var newVal = e.newVal;
        for(var i = 0; i < 5; ++i){
          if(i < newVal){
            stars.eq(i).html(fillStar);
          }else{
            stars.eq(i).html(emptyStar);
          }
        }
      });
    }
  },
  {
    star: {
      value: 3,
      set: toNumber
    },
    el: {
      value: '',
      set: function(v) {
        return $(v);
      }
    },
    width: {
      value: 200,
      set: toNumber
    },
    height: {
      value: 20,
      set: toNumber
    },
    interval: {
      value: 5,
      set: toNumber
    },
    unit: {
      value: 'px'
    },
    editable: {
      value: true
    }
  });
});

